/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Transaction;

import Clases.CCliente;
import Clases.CControlCliente;
import Clases.CProducto;
import Clases.MCCliente;
import Clases.MCDetalleVenta;
import Clases.MCServicioTecnico;
import Clases.MCVenta;
import Modelo.Numero_a_Letra;
import Modelo.Conection;
import Modelo.Functions;
import Presentation.Main;
import java.awt.HeadlessException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import javax.swing.DefaultCellEditor;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author Rudy
 */
public class Venta_recuperada extends javax.swing.JInternalFrame {

    /**
     * Creates new form Venta
     */
    Conection conection=new Conection();
    public static DefaultTableModel modelo,alter;
    Main main=new Main();
    CControlCliente lista=new CControlCliente();
    Numero_a_Letra NumLetra = new Numero_a_Letra();
    Double tipoCambio=0.00;
    ArrayList l1=new ArrayList();
    ArrayList l2=new ArrayList();
    ArrayList l3=new ArrayList();

    
    public Venta_recuperada( Main pmain,String idventa) throws SQLException  {
        initComponents();
        conection.Conectar();
        main=pmain;        
        modelo = (DefaultTableModel)tbl_venta.getModel();
        lbl_nro_venta.setText(String.valueOf(conection.getUltimoId("id_venta","tventa")+1));
        lbl_nro_venta_anterior.setText(idventa);
        conection.cargarComboProducto(cbp_producto);
        AutoCompleteDecorator.decorate(cbp_producto);        
        dc_fecha.setDate(new Date());
        tbl_venta.setRowHeight(25);
        JTextField textField = new JTextField();
        DefaultCellEditor dCE_tf=new DefaultCellEditor(textField);
        tbl_venta.getColumnModel().getColumn(3).setCellEditor(dCE_tf);
        tbl_venta.getColumnModel().getColumn(6).setCellEditor(dCE_tf);
        
        ///codigo para recuperar todos los atributos

        MCVenta V=conection.MrecuperarVenta(idventa);
        MCCliente C=conection.MrecuperarCliente(V.getDni_ruc());
        cbc_cliente.setText(C.getNombre());
        lbl_dni_ruc.setText(C.getDni_ruc());
        txt_fecha_anterior.setText(V.getFecha());
        txttipo.setText(V.getTipo());

        ///////////////codigo para rellenar en la tabla de detalles
        ArrayList<MCDetalleVenta> lista1=conection.MrecuperarDetalleVenta(idventa);

        Object[] fila = new Object[9];
        for(int i=0;i<lista1.size();i++){
            MCDetalleVenta detalle = lista1.get(i);
            fila[0]= i+1;
            String id_productoo=detalle.getId_producto();
            fila[1]= id_productoo;
            l1.add(id_productoo);
            fila[2]= detalle.getDescripcion();
            int cantidad=Integer.parseInt(detalle.getCantidad().toString());
            fila[3]= cantidad;
            l2.add(cantidad);
            double precio_unitario=Double.parseDouble(detalle.getPrecio_unitario().toString());
            fila[4]= precio_unitario;  
            double valor_bruto=cantidad*precio_unitario;
            fila[5]= valor_bruto;
            double porcentaje_descuento=Double.parseDouble(detalle.getPorcentaje_descuento().toString());
            fila[6]= porcentaje_descuento;
            double valor_neto=valor_bruto-(valor_bruto*porcentaje_descuento)/100;
            fila[7]= valor_neto;
            int stok=Integer.parseInt(detalle.getStok());
            fila[8]= stok;
            l3.add(stok);
            modelo.addRow(fila);
        }

        MCServicioTecnico servicio=conection.MrecuperarSV(idventa);
        if (servicio!=null){
            fila[0]= lista1.size();
            fila[3]= servicio.getServicio_tecnico();
            fila[7]= servicio.getPrecio_servicio();
            fila[1]= "";
            fila[2]= "";
            fila[4]= "";
            fila[5]= "";
            fila[6]= "";
            fila[8]= "";
            modelo.addRow(fila);            
        }        
        tbl_venta.setModel(modelo);
        /////////////actualizar los precios/////////////////////
        MetodoCalcularSubTotal();
        
        
    }

    public static DefaultTableModel getModelo() {
        return modelo;
    }

    public void setModelo(DefaultTableModel modelo) {
        this.modelo = modelo;
    }
    
    public CControlCliente getLista() {
        return lista;
    }

    public void setLista(CControlCliente lista) {
        this.lista = lista;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        Label8 = new javax.swing.JLabel();
        lbl_nro_venta = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        lbl_dni_ruc = new javax.swing.JLabel();
        dc_fecha = new com.toedter.calendar.JDateChooser();
        Label5 = new javax.swing.JLabel();
        lbl_nro_venta_anterior = new javax.swing.JLabel();
        cbc_cliente = new javax.swing.JTextField();
        jLabel22 = new javax.swing.JLabel();
        txt_fecha_anterior = new javax.swing.JTextField();
        txttipo = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        cbp_producto = new javax.swing.JComboBox();
        btn_agregar_producto = new javax.swing.JButton();
        btn_eliminar_producto = new javax.swing.JButton();
        btn_servicio_tecnico = new javax.swing.JButton();
        btn_addproduct = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbl_venta = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        lbl_valor_bruto = new javax.swing.JLabel();
        lbl_descuento = new javax.swing.JLabel();
        lbl_valor_neto = new javax.swing.JLabel();
        lbl_recargos = new javax.swing.JLabel();
        lbl_valor_venta = new javax.swing.JLabel();
        lbl_igv = new javax.swing.JLabel();
        lbl_precio_venta = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        lbl_num_letra_en = new javax.swing.JLabel();
        jLabel23 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        jLabel19 = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        lbl_tipoCambio = new javax.swing.JLabel();
        cb_tipo_pago = new javax.swing.JComboBox();
        btn_factura = new javax.swing.JButton();
        btn_ficha_remision = new javax.swing.JButton();

        setTitle("Venta");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Cliente :");

        jLabel2.setText("Fecha :");

        Label8.setFont(new java.awt.Font("Tahoma", 1, 14));
        Label8.setText("Nro:");

        lbl_nro_venta.setFont(new java.awt.Font("Tahoma", 1, 18));
        lbl_nro_venta.setText("0");

        jLabel7.setText("R.U.C / D.N.I :");

        lbl_dni_ruc.setFont(new java.awt.Font("Tahoma", 0, 14));
        lbl_dni_ruc.setText("0");

        dc_fecha.setBackground(new java.awt.Color(255, 255, 255));
        dc_fecha.setEnabled(false);

        Label5.setFont(new java.awt.Font("Tahoma", 1, 14));
        Label5.setText("Nro. Ant.:");

        lbl_nro_venta_anterior.setFont(new java.awt.Font("Tahoma", 1, 18));
        lbl_nro_venta_anterior.setText("0");

        cbc_cliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbc_clienteActionPerformed(evt);
            }
        });

        jLabel22.setText("Fecha Anterior:");

        txt_fecha_anterior.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_fecha_anteriorActionPerformed(evt);
            }
        });

        txttipo.setFont(new java.awt.Font("Tahoma", 1, 14));
        txttipo.setText(":");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lbl_dni_ruc)
                        .addGap(183, 183, 183)
                        .addComponent(txttipo, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
                        .addComponent(Label5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lbl_nro_venta_anterior)
                        .addGap(90, 90, 90)
                        .addComponent(Label8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lbl_nro_venta)
                        .addGap(5, 5, 5))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbc_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(dc_fecha, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel22)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txt_fecha_anterior, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 230, Short.MAX_VALUE)))
                .addGap(165, 165, 165))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel7)
                        .addComponent(lbl_dni_ruc)
                        .addComponent(txttipo))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(Label8)
                        .addComponent(lbl_nro_venta)
                        .addComponent(Label5)
                        .addComponent(lbl_nro_venta_anterior)))
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cbc_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(dc_fecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel22)
                        .addComponent(txt_fecha_anterior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel3.setText("Seleccione Producto :");

        cbp_producto.setEditable(true);

        btn_agregar_producto.setText("Agregar");
        btn_agregar_producto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_agregar_productoActionPerformed(evt);
            }
        });

        btn_eliminar_producto.setText("Eliminar");
        btn_eliminar_producto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_eliminar_productoActionPerformed(evt);
            }
        });

        btn_servicio_tecnico.setText("Servicio Tecnico");
        btn_servicio_tecnico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_servicio_tecnicoActionPerformed(evt);
            }
        });

        btn_addproduct.setText("Agregar");
        btn_addproduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_addproductActionPerformed(evt);
            }
        });

        jButton1.setText("Pruebas");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(cbp_producto, 0, 544, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_agregar_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1)
                        .addGap(75, 75, 75))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(btn_addproduct, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btn_servicio_tecnico, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btn_eliminar_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(42, 429, Short.MAX_VALUE))))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbp_producto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_agregar_producto)
                    .addComponent(jLabel3)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_addproduct)
                    .addComponent(btn_servicio_tecnico)
                    .addComponent(btn_eliminar_producto))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tbl_venta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nro", "Codigo", "Denominacion", "Cantidad", "Precio. Unit", "Valor Bruto", "% Dcto", "Valor Neto", "Stock"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, true, false, false, true, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbl_venta.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbl_ventaMouseClicked(evt);
            }
        });
        tbl_venta.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tbl_ventaKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(tbl_venta);
        tbl_venta.getColumnModel().getColumn(0).setMinWidth(50);
        tbl_venta.getColumnModel().getColumn(0).setPreferredWidth(50);
        tbl_venta.getColumnModel().getColumn(0).setMaxWidth(50);
        tbl_venta.getColumnModel().getColumn(1).setMinWidth(120);
        tbl_venta.getColumnModel().getColumn(1).setPreferredWidth(120);
        tbl_venta.getColumnModel().getColumn(1).setMaxWidth(120);
        tbl_venta.getColumnModel().getColumn(3).setMinWidth(60);
        tbl_venta.getColumnModel().getColumn(3).setPreferredWidth(60);
        tbl_venta.getColumnModel().getColumn(3).setMaxWidth(60);
        tbl_venta.getColumnModel().getColumn(4).setMinWidth(80);
        tbl_venta.getColumnModel().getColumn(4).setPreferredWidth(80);
        tbl_venta.getColumnModel().getColumn(4).setMaxWidth(80);
        tbl_venta.getColumnModel().getColumn(5).setMinWidth(100);
        tbl_venta.getColumnModel().getColumn(5).setPreferredWidth(100);
        tbl_venta.getColumnModel().getColumn(5).setMaxWidth(100);
        tbl_venta.getColumnModel().getColumn(6).setMinWidth(60);
        tbl_venta.getColumnModel().getColumn(6).setPreferredWidth(60);
        tbl_venta.getColumnModel().getColumn(6).setMaxWidth(60);
        tbl_venta.getColumnModel().getColumn(7).setMinWidth(100);
        tbl_venta.getColumnModel().getColumn(7).setPreferredWidth(100);
        tbl_venta.getColumnModel().getColumn(7).setMaxWidth(100);
        tbl_venta.getColumnModel().getColumn(8).setMinWidth(60);
        tbl_venta.getColumnModel().getColumn(8).setPreferredWidth(60);
        tbl_venta.getColumnModel().getColumn(8).setMaxWidth(60);

        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel8.setText("Valor Bruto");

        jLabel9.setText("Descuento");

        jLabel10.setText("Valor Neto");

        jLabel11.setText("Recargos");

        jLabel12.setText("Valor Venta");

        jLabel13.setText("I.G.V");

        jLabel14.setText("Precio Venta");

        lbl_valor_bruto.setFont(new java.awt.Font("Tahoma", 1, 12));
        lbl_valor_bruto.setText("0.00");

        lbl_descuento.setFont(new java.awt.Font("Tahoma", 1, 12));
        lbl_descuento.setText("0.00");

        lbl_valor_neto.setFont(new java.awt.Font("Tahoma", 1, 12));
        lbl_valor_neto.setText("0.00");

        lbl_recargos.setFont(new java.awt.Font("Tahoma", 1, 12));
        lbl_recargos.setText("0.00");

        lbl_valor_venta.setFont(new java.awt.Font("Tahoma", 1, 12));
        lbl_valor_venta.setText("0.00");

        lbl_igv.setFont(new java.awt.Font("Tahoma", 1, 12));
        lbl_igv.setText("0.00");

        lbl_precio_venta.setFont(new java.awt.Font("Tahoma", 1, 12));
        lbl_precio_venta.setText("0.00");

        jLabel15.setText("SON:");

        lbl_num_letra_en.setText("CERO CON 0/100  DOLARES AMERICANOS");

        jLabel23.setText("US$");

        jLabel16.setText("=18%");

        jLabel17.setText("equivalente:");

        jLabel18.setText("CERO SOLES");

        jLabel19.setText("S/.");

        jLabel20.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel20.setText("0.00");

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8)
                            .addComponent(lbl_valor_bruto))
                        .addGap(51, 51, 51)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel9)
                            .addComponent(lbl_descuento))
                        .addGap(67, 67, 67)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel10)
                            .addComponent(lbl_valor_neto))
                        .addGap(60, 60, 60)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel11)
                            .addComponent(lbl_recargos))
                        .addGap(65, 65, 65)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel12)
                            .addComponent(lbl_valor_venta))
                        .addGap(54, 54, 54)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel5Layout.createSequentialGroup()
                                .addComponent(jLabel13)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel16)
                                .addGap(0, 166, Short.MAX_VALUE))
                            .addGroup(jPanel5Layout.createSequentialGroup()
                                .addComponent(lbl_igv)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 181, Short.MAX_VALUE)
                                .addComponent(jLabel23))))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(jLabel15)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbl_num_letra_en)
                        .addGap(46, 46, 46)
                        .addComponent(jLabel17)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel18)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 350, Short.MAX_VALUE)
                        .addComponent(jLabel19)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel14)
                    .addComponent(lbl_precio_venta)
                    .addComponent(jLabel20))
                .addGap(53, 53, 53))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(jLabel9)
                    .addComponent(jLabel10)
                    .addComponent(jLabel11)
                    .addComponent(jLabel12)
                    .addComponent(jLabel13)
                    .addComponent(jLabel14)
                    .addComponent(jLabel16))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_valor_bruto)
                    .addComponent(lbl_descuento)
                    .addComponent(lbl_valor_neto)
                    .addComponent(lbl_recargos)
                    .addComponent(lbl_valor_venta)
                    .addComponent(lbl_igv)
                    .addComponent(lbl_precio_venta)
                    .addComponent(jLabel23))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(lbl_num_letra_en)
                    .addComponent(jLabel17)
                    .addComponent(jLabel18)
                    .addComponent(jLabel19)
                    .addComponent(jLabel20))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 920, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jPanel6.setBackground(new java.awt.Color(204, 204, 255));
        jPanel6.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(204, 0, 0), new java.awt.Color(204, 204, 204)));
        jPanel6.setForeground(new java.awt.Color(255, 255, 255));

        jLabel6.setText("Tipo de Cambio :");

        lbl_tipoCambio.setFont(new java.awt.Font("Tahoma", 1, 14));
        lbl_tipoCambio.setText("0.00");

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addGap(18, 18, 18)
                .addComponent(lbl_tipoCambio)
                .addContainerGap(33, Short.MAX_VALUE))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addGap(0, 8, Short.MAX_VALUE)
                        .addComponent(lbl_tipoCambio))
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(3, 3, 3))
        );

        cb_tipo_pago.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Soles", "Dolares" }));

        btn_factura.setText("Guardar Cambios");
        btn_factura.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_facturaActionPerformed(evt);
            }
        });

        btn_ficha_remision.setText("Ficha de Remision");
        btn_ficha_remision.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ficha_remisionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cb_tipo_pago, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_factura, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_ficha_remision, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 375, Short.MAX_VALUE)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cb_tipo_pago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btn_factura)
                        .addComponent(btn_ficha_remision)))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_agregar_productoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_agregar_productoActionPerformed
        // TODO add your handling code here:
        CProducto P = (CProducto)cbp_producto.getSelectedItem();
        boolean exist=false;
        for (int i = 0; i < modelo.getRowCount(); i++) {
//            if(!((modelo.getValueAt(i, 0).toString().split("-"))[0]).equals("ST:CR"))
//            {
//            System.out.println(P.getIdProducto()+" - "+modelo.getValueAt(i, 1).toString());
                if(P.getIdProducto().equals(modelo.getValueAt(i, 1).toString()))
                { 
                   exist=true;
                   JOptionPane.showMessageDialog(Venta_recuperada.this,"El producto ya existe en la lista, \nSolo edite la cantidad en la tabla.", "ATENCION", JOptionPane.INFORMATION_MESSAGE);
                   i=modelo.getRowCount();   
                }
//            }
        }        
        if(!exist)
        {
            Object D[] ={tbl_venta.getRowCount()+1,P.getIdProducto(),P.getNombre(),1,Functions.round(P.getPrecio_unitario(),2),Functions.round(1*P.getPrecio_unitario(),2),Functions.round(P.getPorcentaje_descuento(),2),Functions.round(1*P.getPrecio_unitario()+(1*P.getPrecio_unitario())*(P.getPorcentaje_descuento()/100),2),P.getStock()};
            modelo.addRow(D);
        }
        MetodoCalcularSubTotal();
    }//GEN-LAST:event_btn_agregar_productoActionPerformed

    private void btn_eliminar_productoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_eliminar_productoActionPerformed
        // TODO add your handling code here:    
        int f= tbl_venta.getSelectedRow();
        //tf_total.setText(String.valueOf(Double.parseDouble(tf_total.getText())-Double.parseDouble(tbl_venta.getValueAt(f, 4).toString())));
        modelo.removeRow(f);
        MetodoCalcularSubTotal();
    }//GEN-LAST:event_btn_eliminar_productoActionPerformed

    private void btn_servicio_tecnicoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_servicio_tecnicoActionPerformed
        // TODO add your handling code here        
//        if(!tf_monto_st.getText().equals(""))
//        {
//            Date date=new Date();
//            String fecha = new SimpleDateFormat("yyMMddhhmm").format(date);
//            modelo = (DefaultTableModel)tbl_venta.getModel();
//
//            Object D[] ={fecha,"Servicio Tecnico","-","-",tf_monto_st.getText(),"-"};
//            modelo.addRow(D);
//        }
//        else
//        {
//            JOptionPane.showMessageDialog(Venta.this,"Ingrese Monto/Costo del Serivio Tecnico", "ATENCION", JOptionPane.INFORMATION_MESSAGE);
//        }
        AddTechnicalService service= new AddTechnicalService(main, closable, conection,main,tipoCambio);
        service.setVisible(true);
    }//GEN-LAST:event_btn_servicio_tecnicoActionPerformed

    private void btn_addproductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_addproductActionPerformed
        // TODO add your handling code here:
        AddProduct produtc= new AddProduct(main, closable, conection);
        produtc.setVisible(true);        
        //int dni_ruc = ((CCliente)cbc_cliente.getSelectedItem()).getDni_ruc();
        //System.out.println(dni_ruc);
        //lbl_dni_ruc.setText(dni_ruc);
    }//GEN-LAST:event_btn_addproductActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
//        Random r=new Random();
//        for (int i = 100; i < 500; i++) {
//            //String v=String.valueOf(r.nextDouble()*100).substring(0, 5);
//            //System.out.println(v);
//            ArrayList columns_save=new ArrayList();
//            columns_save.add("id_producto");
//            columns_save.add("nombre");
//            columns_save.add("descripcion");
//            columns_save.add("precio_unitario");
//            columns_save.add("porcentaje_descuento");
//            columns_save.add("unidad_medida");
//            columns_save.add("stock");
//            columns_save.add("porcentaje_ganancia");
//            columns_save.add("fecha_registro");
//            ArrayList product_data=new ArrayList();
//            product_data.add(i*100+i);
//            product_data.add("producto"+i);
//            product_data.add("descripcion"+i);
//            product_data.add(String.valueOf(r.nextDouble()*100).substring(0, 5));
//            product_data.add(String.valueOf(r.nextDouble()*10).substring(0, 4));
//            product_data.add("um"+1);
//            product_data.add(String.valueOf(r.nextDouble()*1000).substring(0, 3));
//            product_data.add(String.valueOf(r.nextDouble()*10).substring(0, 4));
//            product_data.add(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//            conection.insert(columns_save,product_data, "tproducto");
//        } 
//        Random r=new Random();
//         for (int i = 100; i < 500; i++) {
//            ArrayList columns_save=new ArrayList();
//            columns_save.add("dni_ruc");
//            columns_save.add("nombre");
//            columns_save.add("direccion");
//            columns_save.add("email");
//            columns_save.add("telefono");
//            ArrayList product_data=new ArrayList();
//            product_data.add(String.valueOf(r.nextDouble()*10).substring(3, 12));
//            product_data.add("nombre"+i);
//            product_data.add("direccion"+i);
//            product_data.add("email"+i);
//            product_data.add(String.valueOf(r.nextDouble()*10).substring(3, 12));
//            conection.insert(columns_save,product_data, "tcliente");
//        } 
        
//        for (int i = 1; i < 9; i++) {
//            ArrayList columns_save=new ArrayList();
//            columns_save.add("dni_empleado");
//            columns_save.add("nombre");
//            columns_save.add("usuario");
//            columns_save.add("clave");
//            columns_save.add("direccion");
//            columns_save.add("estado");
//            columns_save.add("telefono");
//            columns_save.add("email");
//            ArrayList product_data=new ArrayList();
//            product_data.add(i*1000000+i);
//            product_data.add("empleado"+i);
//            product_data.add("usuario"+i);
//            product_data.add("clave"+i);
//            product_data.add("direccion"+i);
//            product_data.add("deshabilitado");
//            product_data.add(i+"1"+i+"12789"+i);
//            product_data.add("empleado"+1+"@hotmail.com");
//            conection.insert(columns_save,product_data, "templeado");
//        }
        
//         for (int i = 1; i < 9; i++) {
//            ArrayList columns_save=new ArrayList();
//            columns_save.add("placa");
//            columns_save.add("marca");
//            columns_save.add("modelo");
//            columns_save.add("nro_serie");
//            ArrayList product_data=new ArrayList();
//            product_data.add("pe-"+i*100+i);
//            product_data.add("marca"+i);
//            product_data.add("modelo"+i);
//            product_data.add("nroserie"+i);
//            conection.insert(columns_save,product_data, "tvehiculo");
//        }
        
//        Random r=new Random();
//        for (int i = 500; i < 600; i++) {
//            ArrayList columns_save=new ArrayList();
//            columns_save.add("dni_empleado");
//            columns_save.add("placa");
//            columns_save.add("fecha");
//            columns_save.add("costototal");
//            columns_save.add("desc_general");
//            ArrayList product_data=new ArrayList();
//            int numero=Integer.valueOf(String.valueOf(r.nextDouble()*100000).substring(0, 1));
//            int dni=numero*1000000+numero;
//            System.out.println(dni);
//            product_data.add(dni);
//            int placa=numero*1000+numero;
//            System.out.println(placa);
//            product_data.add("pe-"+placa);
//            product_data.add(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//            product_data.add(String.valueOf(r.nextDouble()*100).substring(0, 4));
//            product_data.add(String.valueOf(r.nextDouble()*100).substring(0, 4));
//            conection.insert(columns_save,product_data, "tservicio_tecnico");
//        }        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void tbl_ventaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbl_ventaKeyReleased
        // TODO add your handling code here:
        try {
            validacionStock();
            MetodoCalcularSubTotal();            
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error:\n Digite valores NUMERICOS\n se recomienda llenar nuevamente el formulario", "Informacion", JOptionPane.ERROR_MESSAGE);
        }        
    }//GEN-LAST:event_tbl_ventaKeyReleased

    private void tbl_ventaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_ventaMouseClicked
        // TODO add your handling code here:
        try {
            validacionStock();
            MetodoCalcularSubTotal();            
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error:\n Digite valores NUMERICOS\n se recomienda llenar nuevamente el formulario", "Informacion", JOptionPane.ERROR_MESSAGE);
        }   
    }//GEN-LAST:event_tbl_ventaMouseClicked

private void cbc_clienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbc_clienteActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cbc_clienteActionPerformed

private void txt_fecha_anteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_fecha_anteriorActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_fecha_anteriorActionPerformed

private void btn_facturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_facturaActionPerformed
        
            // TODO add your handling code here:
    //        try {            
    //            GrabarTransaccion(1);
    //            this.setClosed(true);
    //        } catch (PropertyVetoException ex) {
    //            Logger.getLogger(Venta.class.getName()).log(Level.SEVERE, null, ex);
    //        }
            try {
                String tipo=txttipo.getText();
                if ("factura".equals(tipo)){
                    GrabarTransaccion(1);
                }            
                else if ("boleta".equals(tipo)){
                    GrabarTransaccion(2);
                } 
            }catch (SQLException ex) {
                ex.printStackTrace();
            }
            dispose();
}//GEN-LAST:event_btn_facturaActionPerformed

private void btn_ficha_remisionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ficha_remisionActionPerformed
        try {
            // TODO add your handling code here:
    //        try {            
    //            GrabarTransaccion(4);
    //            this.setClosed(true);
    //        } catch (PropertyVetoException ex) {
    //            Logger.getLogger(Venta.class.getName()).log(Level.SEVERE, null, ex);
    //        }
                    GrabarTransaccion(4);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
}//GEN-LAST:event_btn_ficha_remisionActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel Label5;
    private javax.swing.JLabel Label8;
    private javax.swing.JButton btn_addproduct;
    private javax.swing.JButton btn_agregar_producto;
    private javax.swing.JButton btn_eliminar_producto;
    private javax.swing.JButton btn_factura;
    private javax.swing.JButton btn_ficha_remision;
    private javax.swing.JButton btn_servicio_tecnico;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cb_tipo_pago;
    private javax.swing.JTextField cbc_cliente;
    public static javax.swing.JComboBox cbp_producto;
    public static com.toedter.calendar.JDateChooser dc_fecha;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    public static javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane2;
    public static javax.swing.JLabel lbl_descuento;
    private javax.swing.JLabel lbl_dni_ruc;
    public static javax.swing.JLabel lbl_igv;
    private javax.swing.JLabel lbl_nro_venta;
    private javax.swing.JLabel lbl_nro_venta_anterior;
    public static javax.swing.JLabel lbl_num_letra_en;
    public static javax.swing.JLabel lbl_precio_venta;
    public static javax.swing.JLabel lbl_recargos;
    private javax.swing.JLabel lbl_tipoCambio;
    public static javax.swing.JLabel lbl_valor_bruto;
    public static javax.swing.JLabel lbl_valor_neto;
    public static javax.swing.JLabel lbl_valor_venta;
    public static javax.swing.JTable tbl_venta;
    private javax.swing.JTextField txt_fecha_anterior;
    private javax.swing.JLabel txttipo;
    // End of variables declaration//GEN-END:variables
    
    private void GrabarTransaccion(int tipe) throws SQLException {
        MCCliente cliente = conection.MrecuperarCliente(lbl_dni_ruc.getText().toString());
        ArrayList columns_save=new ArrayList();
        columns_save.add("fecha");
        columns_save.add("dni");
        columns_save.add("dni_ruc");
        columns_save.add("tipo");
        columns_save.add("estado");
        columns_save.add("tipo_cambio");
        columns_save.add("tipo_pago");
        columns_save.add("total_pago");
        
        String fecha = new SimpleDateFormat("yyyy-MM-dd").format(dc_fecha.getDate());
        String tipo="";
        String estado="";
        switch(tipe)
        {
            case 1:
                tipo="factura";
                estado="cancelado";
                break;
            case 2:
                tipo="boleta";
                estado="cancelado";
                break;
            case 3:
                tipo="cotizacion";
                estado="cotizado";
                break;
            case 4:
                tipo="ficha_remision";
                estado="remision";
                break;
        }        
        ArrayList columns_data=new ArrayList();        
        columns_data.add(fecha);
        columns_data.add(Main.getDni());
        columns_data.add(cliente.getDni_ruc());
        columns_data.add(tipo);        
        columns_data.add(estado);
        columns_data.add(Double.valueOf(lbl_tipoCambio.getText()));
        if(cb_tipo_pago.getSelectedIndex()==0){columns_data.add("dolares");}
        if(cb_tipo_pago.getSelectedIndex()==1){columns_data.add("soles");}
        columns_data.add(Double.valueOf(lbl_precio_venta.getText()));
        
        try {
            Actualizar_stok_debuelto();
            conection.insert(columns_save,columns_data, "tventa");            
            GrabarDetalleVenta(tipe);
            conection.Mcambiar_estado_venta(txttipo.getText().toString(),lbl_nro_venta_anterior.getText().toString(),"anulado");            
            JOptionPane.showMessageDialog(this, "Registrado Correctamente", "Informacion", JOptionPane.INFORMATION_MESSAGE);            
        } catch (Exception e) {
                
            JOptionPane.showMessageDialog(this, "Error _ No Registrado Correctamente venta", "Informacion", JOptionPane.ERROR_MESSAGE);
        }
    }
    public void Actualizar_stok_debuelto(){
        for (int i=0;i<l1.size();i++){
            try {
                int stok=(int)l3.get(i)+(int)l2.get(i);
                conection.Mcambiarstok(l1.get(i).toString(),stok);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }            
            
    private void GrabarDetalleVenta(int tipe){
        modelo = (DefaultTableModel)tbl_venta.getModel();
        int rows = modelo.getRowCount();
        int idventa =conection.getUltimoId("id_venta","tventa");
        for (int i = 0; i < rows; i++) {
            if(modelo.getValueAt(i, 0)!=null){
                try {  
                    if(!((tbl_venta.getValueAt(i, 1).toString().split("-"))[0]).equals("ST"))
                    {
                        String idproducto=String.valueOf(tbl_venta.getValueAt(i, 1).toString());
                        ArrayList columns_save=new ArrayList();
                        ArrayList columns_data=new ArrayList();
                        columns_save.add("id_venta");
                        columns_data.add(idventa);
                        System.out.println(idproducto);

                        columns_save.add("id_producto");
                        columns_data.add(idproducto);


                        columns_save.add("precio_unitario");
                        columns_data.add(Double.valueOf(modelo.getValueAt(i, 4).toString()));
                        columns_save.add("cantidad");
                        columns_data.add(Integer.valueOf(modelo.getValueAt(i, 3).toString()));                        
 
                        columns_save.add("unidad_medida");
                        columns_data.add("null");        

                        if(tipe==1||tipe==2)
                        {
                            ArrayList col =new ArrayList();
                            col.add("stock");
                            ArrayList val = new ArrayList();
                            int s = conection.getStock(idproducto);
                            int stk = s-Integer.valueOf(modelo.getValueAt(i,8).toString());
                            val.add(stk);
                            conection.update(col, val, "tproducto", " id_producto ='"+idproducto+"'");
                        }
                        conection.insert(columns_save,columns_data, "tdetalle_venta");
                    }
                    else
                    {
                        String idserviciotecnico=tbl_venta.getValueAt(i, 1).toString().split("-")[1];
                        ArrayList columns_save=new ArrayList();
                        ArrayList columns_data=new ArrayList();
                        columns_save.add("id_venta");
                        columns_data.add(idventa);

                        conection.update(columns_save, columns_data, "tservicio_tecnico", " id_servicio_tecnico ='"+idserviciotecnico+"'");
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    System.out.println("error detalle venta save");
                }
            }
        }        
    }
    public void MetodoCalcularSubTotal() throws NumberFormatException {
        // TODO add your handling code here:
        modelo = (DefaultTableModel)tbl_venta.getModel();
        int fila = modelo.getRowCount();
        double precio_venta=0;
        double valor_bruto=0;
        double descuento=0;
        double valor_neto=0;
        double recargos=0;
        double valor_venta=0;
        double igv=0;
        for (int i = 0; i < fila; i++) {
            double vb=0;
            double dcto=0;
            if(!((tbl_venta.getValueAt(i, 1).toString().split("-"))[0]).equals("ST"))
            {
                vb=Integer.parseInt(modelo.getValueAt(i, 3).toString())*Double.parseDouble(modelo.getValueAt(i, 4).toString());
                dcto=vb*(Double.parseDouble(modelo.getValueAt(i, 6).toString())/100);
                modelo.setValueAt(Functions.round(vb,2), i, 5);
                modelo.setValueAt(Functions.round(vb-dcto,2), i, 7);
            }
            else
            {
                vb=Double.parseDouble(modelo.getValueAt(i, 5).toString());
                dcto=vb*(Double.parseDouble(modelo.getValueAt(i, 6).toString())/100);
            }
            modelo.setValueAt(i+1, i, 0);
            valor_bruto+=vb;
            descuento+=dcto;
            valor_neto+=vb-dcto;
            recargos+=0;
            valor_venta+=vb-dcto;            
            //precio_venta += (Double.parseDouble(modelo.getValueAt(i, 7).toString()));
        }
        igv=valor_venta*0.18;
        precio_venta=valor_venta+igv;
        lbl_precio_venta.setText(String.valueOf(Functions.round(precio_venta,2)));
        lbl_valor_bruto.setText(String.valueOf(Functions.round(valor_bruto,2)));
        lbl_descuento.setText(String.valueOf(Functions.round(descuento,2)));
        lbl_valor_neto.setText(String.valueOf(Functions.round(valor_neto,2)));
        lbl_recargos.setText(String.valueOf(Functions.round(recargos,2)));
        lbl_valor_venta.setText(String.valueOf(Functions.round(valor_venta,2)));
        lbl_igv.setText(String.valueOf(Functions.round(igv,2)));
        
        lbl_num_letra_en.setText(NumLetra.Convertir(String.valueOf(Functions.round(precio_venta,2)),true));
    }
    public void validacionStock() throws HeadlessException, NumberFormatException {
        // TODO add your handling code here:
        int fila = tbl_venta.getRowCount();
            for (int i = 0; i < fila; i++) {
                if(!tbl_venta.getValueAt(i, 1).toString().split("-")[0].equals("ST"))
                {
                    int cant =Integer.parseInt(tbl_venta.getValueAt(i, 3).toString());
                    int st =Integer.parseInt(tbl_venta.getValueAt(i, 8).toString());
                    if(cant>st){
                        JOptionPane.showMessageDialog(this, "Atencion:\n "+tbl_venta.getValueAt(i, 2)+" \n en stock INSUFICIENTE", "Informacion", JOptionPane.WARNING_MESSAGE);
                        tbl_venta.setValueAt(st, i, 3);
                    }      
                }
            }
    }
}

